package com.haitonghop.modules.truyentranh;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.haitonghop.R;
import com.haitonghop.controls.AdsViewControl;
import com.haitonghop.controls.DataCachedControl;
import com.haitonghop.controls.WarperImageView;
import com.haitonghop.data.TamDiemDetailModuleData;
import com.haitonghop.data.TamDiemMetalData;
import com.haitonghop.main.AdsBussiness;
import com.haitonghop.network.APIRequestWorker;
import com.haitonghop.network.Request;
import com.haitonghop.network.RequestListener;
import com.haitonghop.requester.TruyenTranhRequester;
import com.haitonghop.utils.GlobalData;

public class TruyenTranhCategoryActivity extends Activity implements RequestListener, OnItemClickListener {

	LinearLayout loadingPage = null;
	LinearLayout loadingError = null;
	LinearLayout mainContent = null;
	AdsViewControl prviewTamDiem = null;
	GridView imageListView = null;
	TruyenTranhCategoryRender tamDiemRenderAdapter = null;
	boolean isLoading = false;
	LinearLayout hotPanel;
	FrameLayout truyentranhHot;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.truyentranh_category_activity_layout);

		hotPanel = (LinearLayout) findViewById(R.id.hotPanel);
		loadingPage = (LinearLayout) findViewById(R.id.loadingpagetamdiem);
		loadingError = (LinearLayout) findViewById(R.id.loadingError);
		mainContent = (LinearLayout) findViewById(R.id.mainContent);
		prviewTamDiem = (AdsViewControl) findViewById(R.id.prviewTamDiem);
		imageListView = (GridView) findViewById(R.id.imageListView);
		truyentranhHot = (FrameLayout)findViewById(R.id.truyentranhHot);

		truyentranhHot.setVisibility(View.GONE);
		prviewTamDiem.setVisibility(View.VISIBLE);
		loadingError.setVisibility(View.INVISIBLE);

		TextView textView = (TextView) findViewById(R.id.titleActivity);
		textView.setText("Kho truyện tranh");

//		Button button = (Button) findViewById(R.id.btnMoreFunctions);
//		button.setBackgroundResource(android.R.drawable.ic_search_category_default);
//		button.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//
//				Intent itent = new Intent(TruyenTranhCategoryActivity.this, TruyenTranhSearchActivity.class);
//				startActivity(itent);
//			}
//		});

		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					APIRequestWorker.getInstance().clearAllRequests();
					finish();
				}
			});
		}
	}

//	@Override
//	public void onConfigurationChanged(Configuration newConfig) {
//	    super.onConfigurationChanged(newConfig);
//
//	    // Checks the orientation of the screen
//	    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//	    	int width = imageListView.getColumnWidth();
//	    	int column = getWindowManager().getDefaultDisplay().getWidth() / width;
//	    	imageListView.setNumColumns(column);
//	    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
//	    	imageListView.setNumColumns(2);
//	    }
//	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			APIRequestWorker.getInstance().clearAllRequests();
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	void doAdsByServer() {
		AdsBussiness.getInstance().doGetAdsFromServer(this, prviewTamDiem);
	}

	boolean isStart = true;
	@Override
	protected void onStart() {
		super.onStart();
		if(isStart){
			isStart = false;
			onStartUp();
		} else {
			doAdsByServer();
		}

	}

	@SuppressWarnings("unchecked")
	private void onStartUp() {
		init();

		isLoading = true;
		TruyenTranhRequester requester = TruyenTranhRequester.getCategory(TruyenTranhCategoryActivity.this);
		APIRequestWorker.getInstance().addAPIRequest(requester);
	}

	void init() {
	}

	void fillDataIntoAdapter(ArrayList<TamDiemMetalData> arrayList) {
		if (tamDiemRenderAdapter == null) {
			tamDiemRenderAdapter = new TruyenTranhCategoryRender(this, 1, 1, arrayList);
			tamDiemRenderAdapter.useTruyenTranh = true;
			imageListView.setAdapter(tamDiemRenderAdapter);
		} else {
			tamDiemRenderAdapter.setNewData(arrayList);
			tamDiemRenderAdapter.notifyDataSetChanged();
		}
	}

	ArrayList<TamDiemDetailModuleData> requestedDataListHot;
	OnClickListener itemHotClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if(requestedDataListHot != null){
				TamDiemDetailModuleData detailModuleData =  requestedDataListHot.get(v.getId());
				final String href = detailModuleData.getHref();
				if (href != null && !"".equals(href)) {
					Intent intent = new Intent(getApplication(), TruyenTranhChapterListActivity.class);
					intent.putExtra("href", href);
					intent.putExtra("NAME", detailModuleData.getTitle());
					intent.putExtra("AVATAR", detailModuleData.getAvatar());
					TruyenTranhSession.setCurrentComic(detailModuleData);
					startActivity(intent);
				}
			}
		}
	};

	void doAddHot(ArrayList<TamDiemDetailModuleData> requestedDataList){
		this.requestedDataListHot = requestedDataList;
		if(requestedDataList != null){
			for(int i = 0 , n = requestedDataList.size() ; i < n ; i++){

				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View rowHeader = inflater.inflate(R.layout.truyentranh_hot_render_detail_modules, hotPanel, false);
				rowHeader.setPadding(2,2,2,2);
				rowHeader.setId(i);

				final WarperImageView imageView = (WarperImageView) rowHeader.findViewById(R.id.avatarView);

				rowHeader.setOnClickListener(itemHotClick);
				TamDiemDetailModuleData module = requestedDataList.get(i);
				GlobalData.mAQ.id(imageView).image(module.getAvatar(), GlobalData.opt_avatar);

				hotPanel.addView(rowHeader, hotPanel.getChildCount());
			}
		}
	}

	@Override
	public void onRequestComplete(Request request) {
		// TODO Auto-generated method stub
		if (request instanceof TruyenTranhRequester) {
			TruyenTranhRequester r = (TruyenTranhRequester) request;
			JSONObject jsonObject = r.getData();
			final ArrayList<TamDiemMetalData> arrayList = new ArrayList<TamDiemMetalData>();
			if (jsonObject != null) {

				JSONArray jsonArray = null;
				try {
					jsonArray = jsonObject.getJSONArray("data");

					if (jsonArray != null) {
						final int size = jsonArray.length();
						for (int i = 0; i < size; i++) {
							JSONObject datas = jsonArray.getJSONObject(i);
							String id = datas.has(TamDiemMetalData.ID) ? datas.getString(TamDiemMetalData.ID) : "";
							String name = datas.has(TamDiemMetalData.NAME) ? datas.getString(TamDiemMetalData.NAME) : "";
							String caption = "";
							String image = datas.has(TamDiemMetalData.IMAGE) ? datas.getString(TamDiemMetalData.IMAGE) : "";
							TamDiemMetalData haiBLMetalData = new TamDiemMetalData(id, name, caption);
							haiBLMetalData.setImage(image);
							arrayList.add(haiBLMetalData);
						}
					}

					final ArrayList<TamDiemDetailModuleData> requestedDataList = new ArrayList<TamDiemDetailModuleData>();
					try {
						JSONArray jsonArrayHot = jsonObject.getJSONArray("hot");
						final int size = jsonArrayHot.length();
						for (int i = 0; i < size; i++) {
							JSONObject datas = jsonArrayHot.getJSONObject(i);

							String title = datas.has(TamDiemDetailModuleData.TITLE) ? datas.getString(TamDiemDetailModuleData.TITLE) : "";
							String avatar = datas.has(TamDiemDetailModuleData.AVATAR) ? datas.getString(TamDiemDetailModuleData.AVATAR) : "";
							String href = datas.has(TamDiemDetailModuleData.HREF) ? datas.getString(TamDiemDetailModuleData.HREF) : "";

							TamDiemDetailModuleData detailModuleData = new TamDiemDetailModuleData(title, avatar, href);
							requestedDataList.add(detailModuleData);
						}
					} catch (Exception e) {
					}

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							truyentranhHot.setVisibility(View.VISIBLE);
							doAddHot(requestedDataList);
						}
					});

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			DataCachedControl.getInstance().putCached(DataCachedControl.TRUYENTRANH_CATEGORY, arrayList);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {

					imageListView.setOnItemClickListener(TruyenTranhCategoryActivity.this);
					loadingError.setVisibility(View.GONE);
					loadingPage.setVisibility(View.GONE);
					imageListView.setVisibility(View.VISIBLE);

					fillDataIntoAdapter(arrayList);
					isLoading = false;

					doAdsByServer();
				}
			});
		}
	}

	@Override
	public void onRequestFailed(String errorMsg, Request request) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				loadingPage.setVisibility(View.GONE);
				loadingError.setVisibility(View.VISIBLE);

				isLoading = false;

				doAdsByServer();
			}
		});
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View arg1, int index, long arg3) {
		if (tamDiemRenderAdapter != null) {
			final String id = tamDiemRenderAdapter.getItem(index).getId();
			if (id != null && !"".equals(id)) {
				Intent intent = new Intent(getApplication(), TruyenTranhDetailCategoryActivity.class);
				intent.putExtra("ID", id);
				intent.putExtra("NAME", tamDiemRenderAdapter.getItem(index).getName());
				startActivity(intent);
			}
		}
	}
}
